package com.xiaoyu.izf.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xiaoyu.izf.config.SysConfig;
import com.xiaoyu.izf.model.*;
import com.xiaoyu.izf.repository.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.sql.Date;

@Service
public class YqfDataGetService {
    @Autowired
    private YqfMerchantDao yqfMerchantDao;
    @Autowired
    private YqfStoreDao yqfStoreDao;
    @Autowired
    private YqfStoreSatsDayDao yqfStoreSatsDayDao;
    @Autowired
    private YqfStoreStatsDayPayWayDao yqfStoreStatsDayPayWayDao;
    @Autowired
    private YqfStoreStatsDayPayClientDao yqfStoreStatsDayPayClientDao;
    @Autowired
    private MerchantInfoDao merchantInfoDao;
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private YqfStoreStatsService yqfStoreStatsService;
    @Autowired
    private YqfCommissionSerialLogService yqfCommissionSerialLogService;

    /**
     * 商户信息
     */
    public void merchantInfoGet() {
        String host = SysConfig.yqfHost + "public/admin/find_all_merchant";
        String rs = HttpUtil.get(host);
        //System.out.println(rs);
        if (!StringUtils.isEmpty(rs)) {
            JSONObject jsonObjectRs = JSON.parseObject(rs);
            if (jsonObjectRs.getIntValue("code") == 200 && "success".equals(jsonObjectRs.getString("msg"))) {
                JSONArray jsonArray = jsonObjectRs.getJSONArray("obj");
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject json = jsonArray.getJSONObject(i);
                    String id = json.getString("id");
                    YqfMerchant merchant = yqfMerchantDao.findOneById(id);
                    if (merchant == null) {
                        merchant = new YqfMerchant();
                        merchant.setId(id);
                        merchant.setMerchantName(json.getString("name"));
                        merchant.setContact(json.getString("contact"));
                        merchant.setPhone(json.getString("phone"));
                        merchant.setUid(0);
                        merchant.setIsView(0);
                        merchant.setRegionCode("");
                    }
                    MerchantInfo mi = merchantInfoDao.findOneByMerchantNameAndLinkmanMobile(merchant.getMerchantName(), merchant.getContact());
                    if (mi != null) {
                        merchant.setIsView(1);
                        merchant.setUid(mi.getParUid());
                        merchant.setRegionCode(mi.getRegionCode());
                    }
                    yqfMerchantDao.save(merchant);
                }
            }
        }
    }

    /**
     * 门店信息
     */
    public void storeGet() {
        String host = SysConfig.yqfHost + "public/admin/find_all_store";
        String rs = HttpUtil.get(host);
        System.out.println(rs);
        if (!StringUtils.isEmpty(rs)) {
            JSONObject jsonObjectRs = JSON.parseObject(rs);
            if (jsonObjectRs.getIntValue("code") == 200 && "success".equals(jsonObjectRs.getString("msg"))) {
                JSONArray jsonArray = jsonObjectRs.getJSONArray("obj");
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject json = jsonArray.getJSONObject(i);
                    String id = json.getString("id");
                    YqfStore store = yqfStoreDao.findOneById(id);
                    if (store == null) {
                        store = new YqfStore();
                        store.setId(id);
                        store.setStoreName(json.getString("name"));
                        store.setStoreNo(json.getInteger("storeNo"));
                        store.setProvince(json.getString("province"));
                        store.setCity(json.getString("city"));
                        store.setPhone(json.getString("phone"));
                        store.setMerchantId(json.getString("merchantId"));
                        store.setMerchantName(json.getString("merchantName"));
                        yqfStoreDao.save(store);
                    }
                }
            }
        }
    }

    public void storeStateDayGet(String recDate) {
        String host = SysConfig.yqfHost + "public/admin/order_statistics_by_store?beginTime=" + recDate + "&endTime=" + recDate;
        String rs = HttpUtil.get(host);
        if (!StringUtils.isEmpty(rs)) {
            JSONObject jsonObjectRs = JSON.parseObject(rs);
            if (jsonObjectRs.getIntValue("code") == 200 && "success".equals(jsonObjectRs.getString("msg"))) {
                JSONArray jsonArray = jsonObjectRs.getJSONArray("obj");
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject json = jsonArray.getJSONObject(i);
                    String storeId = json.getString("storeId");
                    YqfStoreStatsDay day = yqfStoreSatsDayDao.findByStoreIdAndRecDate(storeId, DateUtil.parseDate(recDate));
                    if (day == null) {
                        day = new YqfStoreStatsDay();
                        day.setStoreId(storeId);
                        day.setRecDate(new Date(DateUtil.parseDate(recDate).getTime()));
                    }
                    day.setStoreName(json.getString("storeName"));
                    day.setOrderAmount((int) (json.getDoubleValue("orderAmount") * 100));
                    day.setValidOrderCount(json.getIntValue("validOrderCount"));
                    day.setValidOrderAmount((int) (json.getDoubleValue("validOrderAmount") * 100));
                    day.setRefundCount(json.getIntValue("refundCount"));
                    day.setRefundAmount((int) (json.getDoubleValue("refundAmount") * 100));
                    day.setCommission((int) (json.getDoubleValue("commission") * 100));
                    day.setIncome((int) (json.getDoubleValue("income") * 100));
                    day.setDiscountAmount((int) (json.getDoubleValue("discountAmount") * 100));
                    day.setRefundProportion(json.getDoubleValue("refundProportion"));
                    day = yqfStoreSatsDayDao.save(day);

                    //计算流水分佣
                    computeSerialCommission(day);

                    JSONArray payWayProportion = json.getJSONArray("payWayProportion");
                    JSONArray payClientProportion = json.getJSONArray("payClientProportion");
                    for (int j = 0; j < payWayProportion.size(); j++) {
                        JSONObject payWayJson = payWayProportion.getJSONObject(j);
                        YqfStoreStatsDayPayWay yssdpw = yqfStoreStatsDayPayWayDao.findByYssdIdAndPayWayName(day.getId(), payWayJson.getString("name"));
                        if (yssdpw == null) {
                            yssdpw = new YqfStoreStatsDayPayWay();
                            yssdpw.setYssdId(day.getId());
                            yssdpw.setPayWayName(payWayJson.getString("name"));
                        }
                        yssdpw.setProportion(payWayJson.getDoubleValue("proportion"));
                        yssdpw.setPayAmount((int) (payWayJson.getDoubleValue("value") * 100));
                        yqfStoreStatsDayPayWayDao.save(yssdpw);
                    }
                    for (int j = 0; j < payClientProportion.size(); j++) {
                        JSONObject payClientJson = payClientProportion.getJSONObject(j);
                        YqfStoreStatsDayPayClient yssdpc = yqfStoreStatsDayPayClientDao.findByYssdIdAndClientName(day.getId(), payClientJson.getString("name"));
                        if (yssdpc == null) {
                            yssdpc = new YqfStoreStatsDayPayClient();
                            yssdpc.setYssdId(day.getId());
                            yssdpc.setClientName(payClientJson.getString("name"));
                        }
                        yssdpc.setProportion(payClientJson.getDoubleValue("proportion"));
                        yssdpc.setPayAmount((int) (payClientJson.getDoubleValue("value") * 100));
                        yqfStoreStatsDayPayClientDao.save(yssdpc);
                    }
                }
            }
        }

    }

    /**
     * 根据每天的门店流水计算出相关合伙人的流水佣金
     *
     * @param day
     */
    @Transactional
    public void computeSerialCommission(YqfStoreStatsDay day) {
        YqfStore store = yqfStoreDao.findOneById(day.getStoreId());
        YqfMerchant merchant = yqfMerchantDao.findOneById(store.getMerchantId());
        //分佣原金额
        int amount = day.getIncome();

        //直推用户
        UserInfo directUser = userInfoDao.findOneById(merchant.getUid());
        boolean innerRegion = yqfStoreStatsService.innerRegion(directUser, merchant);
        double rate1 = yqfStoreStatsService.getRate(1, innerRegion, directUser.getVipType());
        double amount1 = NumberUtil.round(yqfStoreStatsService.serialCommission(amount, rate1), 2).doubleValue();
        yqfCommissionSerialLogService.add(amount, rate1, amount1, directUser.getId(), directUser.getId(), day.getId());
        double commissionSerial1 = directUser.getCommissionSerial() == null ? 0 : directUser.getCommissionSerial();
        directUser.setCommissionSerial(commissionSerial1 + amount1);
        userInfoDao.save(directUser);

        //商户所属省级服务商和区县服务商
        UserInfo provinceUser = userInfoDao.findByRegionCode(merchant.getRegionCode().substring(0, 2) + "0000");
        double rate2 = yqfStoreStatsService.getRate(2, false, provinceUser.getVipType());
        if (provinceUser != null && provinceUser.getId() != directUser.getId()) {
            double amount2 = NumberUtil.round(yqfStoreStatsService.serialCommission(amount, rate2), 2).doubleValue();
            yqfCommissionSerialLogService.add(amount, rate2, amount2, directUser.getId(), provinceUser.getId(), day.getId());
            double commissionSerial2 = provinceUser.getCommissionSerial() == null ? 0 : provinceUser.getCommissionSerial();
            provinceUser.setCommissionSerial(commissionSerial2 + amount2);
            userInfoDao.save(provinceUser);
        }

        UserInfo regionUser = userInfoDao.findByRegionCode(merchant.getRegionCode());
        double rate3 = yqfStoreStatsService.getRate(2, false, regionUser.getVipType());
        if (regionUser != null && regionUser.getId() != directUser.getId()) {
            double amount3 = NumberUtil.round(yqfStoreStatsService.serialCommission(amount, rate3), 2).doubleValue();
            yqfCommissionSerialLogService.add(amount, rate3, amount3, directUser.getId(), regionUser.getId(), day.getId());
            double commissionSerial3 = regionUser.getCommissionSerial() == null ? 0 : regionUser.getCommissionSerial();
            regionUser.setCommissionSerial(commissionSerial3 + amount3);
            userInfoDao.save(regionUser);
        }

        //间推用户
        UserInfo indirectUser = userInfoDao.findOneById(directUser.getPushUid());
        double rate4 = yqfStoreStatsService.getRate(3, false, indirectUser.getVipType());
        if (indirectUser != null &&
                (indirectUser.getVipType() == 1 || indirectUser.getVipType() == 23 || indirectUser.getVipType() == 21)
                && (directUser.getVipType() == 1 || directUser.getVipType() == 2 || directUser.getVipType() == 3)) {
            double amount4 = NumberUtil.round(yqfStoreStatsService.serialCommission(amount, rate4), 2).doubleValue();
            yqfCommissionSerialLogService.add(amount, rate4, amount4, directUser.getId(), indirectUser.getId(), day.getId());
            double commissionSerial4 = indirectUser.getCommissionSerial() == null ? 0 : indirectUser.getCommissionSerial();
            indirectUser.setCommissionSerial(commissionSerial4 + amount4);
            userInfoDao.save(indirectUser);
        }
    }

}
